package com.zhuojy.equity.mall.admin.service;

import cn.hutool.core.util.ObjUtil;
import com.zhuojy.equity.mall.admin.common.exception.Asserts;
import com.zhuojy.equity.mall.admin.dal.dataobject.TResourceDO;
import com.zhuojy.equity.mall.admin.dal.dataobject.TUserDO;
import com.zhuojy.equity.mall.admin.manager.ResourceManager;
import com.zhuojy.equity.mall.admin.manager.RoleResourceRelationManager;
import com.zhuojy.equity.mall.admin.manager.UserManager;
import com.zhuojy.equity.mall.admin.manager.UserRoleRelationManager;
import com.zhuojy.equity.mall.admin.manager.bo.AdminUserDetails;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 用户登录验证处理
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminUserDetailsService implements UserDetailsService {

    private final UserManager userManager;
    private final UserRoleRelationManager userRoleRelationManager;
    private final RoleResourceRelationManager roleResourceRelationManager;
    private final ResourceManager resourceManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("CALL loadUserByUsername REQUEST {}", username);
//		UserDetails userDetails = loginCore.loadUserByUsername(username);
        // 查询用户
        TUserDO tUserDO = userManager.queryUserByUsername(username);
        if (ObjUtil.isNull(tUserDO)) {
            Asserts.UsernameNotFoundException();
        }
        // 查询角色id列表
        List<Long> roleIdList = userRoleRelationManager.queryRoleIdListByUserId(tUserDO.getId());
        // 查询资源id列表
        List<Long> resourceIdList = roleResourceRelationManager.queryResourceIdListByRoleIds(roleIdList);
        // 查询资源对象列表
        List<TResourceDO> resourceDOList = resourceManager.queryByIdList(resourceIdList);
        return new AdminUserDetails(tUserDO, resourceDOList);
    }
}
